<script setup lang="ts">

import {addTips, putTips, type TipsDto} from "@/apis/tips";
import MediaSelect, {type Media} from "@/components/MediaSelect/index.vue";
import type {Ref} from "vue-demi";
import {useUserStore} from "@/stores";

const visible = defineModel('visible', {
  type: Boolean,
  default: false
})

const user = useUserStore().userInfo

const dto:Ref<TipsDto> = defineModel('dto', {
  default: () => {
    return {
      id: 0,
      title: '',
      content: '',
      ossIds: [],
      status: 1,
      updateBy: '',
      updateTime: ''
    }
  }
})

const emit = defineEmits(["put","add"]);

const imgs:Ref<Media[]> = defineModel('imgs', {
  default: () => []
})

const handleOk = () => {

  imgs.value.forEach(i => {
    dto.value.ossIds.push(i.id!)
  })

  if (dto.value.id !== 0) {
    dto.value.updateBy = user.id
    putTips(dto.value).then(() => {
      emit("put")
    })

  } else {
    dto.value.updateBy = user.id
    addTips(dto.value).then(() => {
      emit("add",dto.value)
    })

  }
  visible.value = false
}

const selectMediaHandler = (media: Ref<Media[]>) => {
  imgs.value = media.value
}

const delMediaHandler = (media: Media) => {
  imgs.value = imgs.value.filter(i => i.id !== media.id)
}

const clear = () => {
  dto.value.id = 0
  dto.value.title = ''
  dto.value.content = ''
  dto.value.ossIds = []
  dto.value.status = 1
  imgs.value = []
}

const cancelHandler = () => {
  visible.value = false
  clear()
}

</script>

<template>
  <a-modal
      v-model:visible="visible"
      width="1000px"
      :title="dto.id ? '编辑小贴士' : '新增小贴士'"
      @ok="handleOk"
      @cancel="cancelHandler"
  >
    <a-form :model="dto">
      <a-form-item label="标题" field="title" required>
        <a-input v-model="dto.title" placeholder="请输入标题" />
      </a-form-item>

      <a-form-item label="内容" field="content" required>
        <a-textarea
            v-model="dto.content"
            placeholder="请输入内容"
            show-word-limit
            :max-length="1200"
            :auto-size="{ minRows: 10 }"
        />
      </a-form-item>

      <a-form-item label="图片上传" field="ossIds">
        <MediaSelect width="200" height="100" :isImg="true" :mediaSrc="imgs"
                     @selectMedia="selectMediaHandler"
                     @delMedia="delMediaHandler"
        />
      </a-form-item>

      <a-form-item label="状态" field="status" required>
        <a-select v-model="dto.status">
          <a-option :value="1">启用</a-option>
          <a-option :value="0">禁用</a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="scss">

</style>